<?php
/**
 * Create a new Medical Study - Main Screen
 * 
 * @author Xavier VILAIN
 * @package Nawa\MedicalStudy
 * @license #license#
 * 
 */
use Nawa\Messages;
use Nawa\Customer;
use Nawa\MedicalStudy;
use Nawa\MedicalStudy\Customizing;
use Nawa\MedicalStudy\Partner;
use Fox\Generator;
use Fox\Html\Header\Image;
use Fox\Core\Errors;
use Fox\Html\Button;
use Fox\Html\Screen;

// Load Breadcrumb Data
$id = Xview::instance()->val('sourceid');
try {
	$customer = Fox\Dao::load(Customer::className(),$id);
	$data['customerid'] = $customer->getId();
}
catch(Fox\Object\Exception\NotExist $e)
{
	$customer = new Customer();
	$data = array();
}

$screen = new Screen('sMS','create');
// Bread Crumb
$crumbs = Xview::instance()->component('medicalstudies','breadcrumb',
	array('deepness' => 1,
		'customerid' => $customer->getId(),
		'customer_name' => $customer->name1));
$screen->breadcrumb()->crumbs($crumbs);

$screen->mainTitle(new Image('medicalstudy',"<div class=\"page-title\">".Msg(Messages::BUNDLE,Messages::LABEL_MS_CREATE_NEW)."</div>"));
$screen->toolbar()->add(new Button('copy',
Generator::display('msCopy',
Generator::url('medicalstudies','bycopy')),
Msg(Fox\Msg::BUNDLE,Fox\Msg::BUT_CREATE_BY_COPY)));
// Master Data
$bHeader = Xview::instance()->component('medicalstudies', 'header');
$screen->add($bHeader);
if($customer->exists()) {
	$bHeader->item('customerid')->input(false);
}
$bHeader->item('status')->input(false);
$screen->initialize($data);

if($screen->submitted())
{
	$fields = $screen->get();
	if(!$screen->errors())
	{
		try {
			$ms = new MedicalStudy();
			$fields['type'] = MedicalStudy::TYPE_BASIC;
			$fields['status'] = MedicalStudy::STATUS_OPEN;
			$ms->setFields($fields);
			$ms->responsibleid = User::current()->getId();
			
			// Customer
			$partner = new Partner();
			$partner->setFields(array('customerid' => $fields['customerid'],
									  'role' => MedicalStudy::ROLE_CUSTOMER));
			$ms->addToPartners($partner);
			// Creator
			$creatorid = User::current()->contactId();
			$partner = new Partner();
			$partner->setFields(array('customerid' => User::current()->contactId(),
									  'role' => MedicalStudy::ROLE_ADMIN));
			$ms->replacePartners($partner);
			$ms->create();
			$screen->redirect(Generator::url('medicalstudies','update',null,array('msid' => $ms->getId())));
		}
		catch (Fox\Object\Exception\Save $e) {
			Fox\Message::Error($e);
		}
	}
}
echo $screen->display();